import React, { useEffect, useState, ReactNode } from "react"
import styles from "./main-area.module.css"
import { Button, Divider, Result, Skeleton, Spin } from "antd"
import httpClient from "@/renderer/data/remote/wan-android-api"
import ScrollView from "@/renderer/component/ScrollView"
interface PropsMainArea {
    compClass: string
}
/**
 * 内容区域
 */
const MainArea = ({ compClass }: PropsMainArea) => {
    const [index, setIndex] = useState(0)
    const [initStatus, setInit] = useState(false) // 列表是否已经初始化：加载第一页数据成功，不为空 也没有发生异常
    const [emptyStatus, setEmpty] = useState(false) // 第一次加载 false 不为空 true 无数据
    const [errorStatus, setError] = useState(false) // 第一次加载 false 没异常 true 有异常
    const [loadMoreStatus, setLoadMore] = useState("loading") // loading error completed
    const [list, setList] = useState(Array<ArticeBean>)

    // 网络请求
    async function requestArticeList() {
        try {
            const response = await httpClient.get<PageBean<ArticeBean>>(`article/list/${index}/json`)
            const page = response.data
            if (page.curPage === 1) {
                // 首页数据
                if (page.datas.length === 0) {
                    setEmpty(true)
                } else {
                    setInit(true)
                    setList(page.datas)
                }
            } else if (page.over) {
                //没有更多数据
                setLoadMore("completed")
            } else {
                //加载更多数据
                setList([...list, ...page.datas])
                setLoadMore("loading")
            }
        } catch (error) {
            if (!initStatus) {
                setError(true)
            } else {
                setLoadMore("error")
            }
        }
    }


    function handleArticleListLoderMoew(){
        console.log("======触发加载更多=====")
        setIndex(index + 1)
    }

    //加载更多点击重试
    function handleLoadMoreRetry() {
        setLoadMore("loading")
        requestArticeList()
    }

    useEffect(() => {
        requestArticeList()
    }, [index])

    //根据条件组装UI
    let viewContent: ReactNode

    if (emptyStatus) {
        // 列表加载后 发现没得数据
        viewContent = (
            <Result
                style={{
                    margin: 'auto 0'
                }}
                title="列表暂无数据" />
        )
    } else if (errorStatus) {
        // 列表第一次加载 有异常
        viewContent = (
            <Result
                status="error"
                title="列表加载失败"
                style={{
                    margin: 'auto 0'
                }}
                extra={[
                    <Button type="primary" onClick={() => {
                        setIndex(0)
                    }}>
                        重试
                    </Button>
                ]}
            >
            </Result>
        )
    } else if (!initStatus) {
        //列表未加载
        viewContent = <Skeleton style={{ marginTop: 30 }}></Skeleton>
    } else {
        viewContent = <ArticeList list={list}></ArticeList>
    }


    return (
        <ScrollView className={compClass} onLoadMoreListener={handleArticleListLoderMoew}>
            <TopRecommend></TopRecommend>
            {viewContent}
            {initStatus ? <LoadMoreView status={loadMoreStatus} onRetryListener={handleLoadMoreRetry}></LoadMoreView> : <></>}
        </ScrollView>
    )
}

/**
 * 置顶推荐 没有找到合适的接口 就写成静态的吧
 */
function TopRecommend() {
    return (
        <div className={styles.top_recommend}>
            <div className={`${styles.container}`}>
                <div className={styles.top_header}>
                    <h2>最新学习路线</h2>
                    <a>更多&gt;</a>
                </div>
                <ol>
                    <li className={styles.top_item}>
                        <i></i>
                        <a>鸿蒙App开发入门 - 学习路径</a>
                    </li>
                    <li className={styles.top_item}>
                        <i></i>
                        <a>Android性能优化-长期分享-BaguTree组织</a>
                    </li>
                    <li className={styles.top_item}>
                        <i></i>
                        <a>Android自定义view - 学习路径</a>
                    </li>
                </ol>
            </div>
            <div>
                <Divider type="vertical" style={{ height: 140 }}></Divider>
            </div>
            <div className={`${styles.container} ${styles.right_border}`}>
                <div className={styles.top_header}>
                    <h2>最受欢迎的问答</h2>
                    <a>更多&gt;</a>
                </div>
                <ol>
                    <li className={styles.top_item}>
                        <i></i>
                        <a>每日一问｜Dialog的构造方法的context必须传入Activity吗？</a>
                    </li>
                    <li className={styles.top_item}>
                        <i></i>
                        <a>每日一问｜我们经常说到的Android脱糖指的是什么？</a>
                    </li>
                    <li className={styles.top_item}>
                        <i></i>
                        <a>每日一问｜如何在崩溃时，获得logcat信息？</a>
                    </li>
                </ol>
            </div>
            <Divider type="vertical" style={{ height: 140 }}></Divider>
            <div className={styles.container}>
                <div className={styles.top_header}>
                    <h2>最受欢迎专栏</h2>
                    <a>更多&gt;</a>
                </div>
                <ol>
                    <li className={styles.top_item}>
                        <i></i>
                        <a>Kotlin</a>
                    </li>
                    <li className={styles.top_item}>
                        <i></i>
                        <a>自定义控件</a>
                    </li>
                    <li className={styles.top_item}>
                        <i></i>
                        <a>Jetpack</a>
                    </li>
                </ol>
            </div>
        </div>
    )
}

interface PageBean<T> {
    curPage: number,
    datas: Array<T>,
    offset: number,
    over: boolean,
    pageCount: number,
    size: number,
    total: number
}

interface ArticeBean {
    "id": number,
    "chapterId": number,
    "chapterName": string,
    "superChapterId": string,
    "superChapterName": string,
    "shareUser": string,
    "collect": boolean,
    "title": string,
    "author": string,
    "link": string,
    "fresh": boolean,
    "niceShareDate": string,
    "tags": Array<ArticleTagBean>
}

interface ArticleTagBean {
    "name": string,
    "url": string
}

interface PropsArticeList {
    "list": Array<ArticeBean>
}
/**
 * 文章列表 只做UI展示 不做数据处理
 */
function ArticeList({ list }: PropsArticeList) {
    return (
        <div id="nest-list" className={styles.article_list}>
            {
                list.map((item) => {
                    const hasAuthor = item.shareUser.length === 0
                    const authorLabel = hasAuthor ? "作者：" : "分享人："
                    const author = hasAuthor ? item.author : item.shareUser

                    return (
                        <div key={item.id} className={styles.article_item}>
                            <p className={styles.item_title}>
                                {item.fresh ? <em>新</em> : <></>}
                                <a>{item.title}</a>
                            </p>
                            <div className={styles.item_desc}>
                                {
                                    item.tags.length !== 0 ?
                                        (
                                            item.tags.map((tag) => {
                                                return <span key={tag.name} className={`${styles.space_mr_16} ${styles.item_tag}`}>{tag.name}</span>
                                            })
                                        )
                                        :
                                        (
                                            <></>
                                        )
                                }
                                <span>{authorLabel}</span> <a className={styles.space_mr_16}>{author}</a>
                                <span>分类：</span> <a>{item.superChapterName}</a> <span> / </span> <a className={styles.space_mr_16}>{item.chapterName}</a>
                                <span>时间：{item.niceShareDate}</span>
                            </div>
                        </div>
                    )
                })
            }
        </div>
    )

}

interface PropsLoadMore {
    "status": string
    onRetryListener(): void
}

/**
 * 加载更多
 * @param status loading , error , completed
 */
const LoadMoreView = ({ status, onRetryListener }: PropsLoadMore) => {
    const clazz = {
        padding: "20px 0",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
    }
    const onClickListener = (e: React.UIEvent) => {
        onRetryListener()
    }
    if (status === "loading") {
        return (
            <div style={clazz}>
                <Spin></Spin>
            </div>
        )
    } else if (status === "error") {
        return (
            <div style={clazz} onClick={onClickListener}>数据加载失败，点击重试</div>
        )
    } else if (status === "completed") {
        return (
            <div style={clazz}>没有更多数据</div>
        )
    } else {
        return (
            <div style={clazz}>传错值了熬</div>
        )
    }
}

export default MainArea